/*
 * @Author: zhangzhen
 * @Date: 2022-07-05 14:11:55
 * @LastEditors: zhangzhen
 * @LastEditTime: 2023-04-18 13:04:11
 * @Description:
 *
 */

import { Input, AutoComplete } from 'antd'
import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import { getBaiduSearchInfo } from '../../services'
import { useAppSelector } from '@/redux/hook'
import { shallowEqual } from 'react-redux'

interface optionsType {
  value: string
}

const SearchBox = () => {
  const [options, setOptions] = useState<optionsType[]>([])
  const [inputValue, setInputValue] = useState<string>('')

  const { searchValue } = useAppSelector(
    ({ state }) => ({
      ...state.configs
    }),
    shallowEqual
  )

  const searchInfo = (e: any) => {
    if (searchValue === '1') {
      window.open(`https://www.baidu.com/s?wd=${e}`)
    }

    if (searchValue === '2') {
      window.open(`https://cn.bing.com/search?q=${e}`)
    }
  }

  const getSeachText = (val: string) => {
    getBaiduSearchInfo({
      wd: val,
      prod: 'pc',
      csor: val.length
    }).catch((res) => {
      if (res.g) {
        const resultArr = res?.g.map((item: { q: string }) => {
          return { value: item.q }
        })
        setOptions(resultArr)
      } else {
        setOptions([])
      }
    })
  }

  const inputChange = (value: string) => {
    setInputValue(value)
    getSeachText(value)
  }

  const searchInput = (
    <Input
      value={inputValue}
      size="large"
      bordered={false}
      placeholder="输入并搜索..."
      prefix={
        <img
          className={styles.searchInputPre}
          src={searchValue === '1' ? '/src/assets/baidu.png' : '/src/assets/biying.png'}
        ></img>
      }
      className={styles.searchInput}
      onPressEnter={() => {
        setTimeout(() => searchInfo(inputValue), 0)
      }}
      onChange={(e) => {
        inputChange(e.target.value)
      }}
    />
  )

  return (
    <div className={styles.searchBox}>
      <AutoComplete
        onChange={(e: string) => {
          setInputValue(e)
        }}
        onSelect={(e: string) => {
          searchInfo(e)
        }}
        options={options}
        popupClassName={styles.searchBoxPopup}
      >
        {searchInput}
      </AutoComplete>
    </div>
  )
}

export default SearchBox
